package aliyun

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-playground/validator/v10"
	"mygoedu/day08/cloudstation/store"
	"strings"
)

var validate *validator.Validate

func NewUploader(endpoint, ak, sk string) store.Uploader {
	return &aliyun{
		Endpoint: endpoint,
		Ak:       ak,
		Sk:       sk,
	}
}

type aliyun struct {
	Endpoint string `validate:"required"`
	Ak       string `validate:"required"`
	Sk       string `validate:"required"`
}

func (a *aliyun) validate() error {
	return validate.Struct(a)
}

func (a *aliyun) UploadFile(bucketName, objectkey, filePath string) error {
	client, err := oss.New(a.Endpoint, a.Ak, a.Sk)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	//上传文件
	fileSplit := strings.Split(filePath, "/")
	fileName := fileSplit[len(fileSplit)-1]
	err = bucket.PutObjectFromFile(fileName, filePath)
	if err != nil {
		return err
	}

	//打印下载URL
	signUrl, err := bucket.SignURL("sdd.mod", oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("sign file download error,%s", err)
	}
	fmt.Printf("下载链接: %s\n", signUrl)
	fmt.Println("\n注意: 文件下载有效期1天，中转站保存时间3天")
	return nil
}
